import { PlusOutlined } from '@ant-design/icons'
import { Col, Form, Input, message, Modal, Row, Spin, Upload } from 'antd'
import { connect } from 'dva'
import React, { Component } from 'react'
import WangEditor from '../WangEditor'
import styles from './styles.less'

const { TextArea } = Input
function mapStateToProps({ projectModel }) {
  return {
    projectModel: projectModel,
  }
}
@connect(mapStateToProps)
export default class Details extends Component {
  constructor(props) {
    super(props)
    this.state = {
      coverImg: {}, //封面图片地址
      logoImg: {}, //学校logo地址
      listImage: [], //介绍资料地址
      coverVideo: {}, //学校视频
      publicityText: '', //学校风采宣传text
      companyProfile: null,
      campusLowCarbon: null,
      updateOraffirm: false, //false：新增，true：编辑
      editor: null,
      editor2: null,
      slogan: '',
      videoSpin: false,
      coverSpin: false,
      logoSpin: false,
      listSpin: false,
    }
    this.formRef = React.createRef()
  }

  componentDidMount() {
    let { mineDetails, mineState } = this.props
    if (mineState) {
      this.setState(
        {
          coverImg: { url: mineDetails.coverImage },
          logoImg: { url: mineDetails.companyLogo },
          listImage: mineDetails.listImage,
          coverVideo:
            mineDetails.corporateVideo && mineDetails.corporateVideo !== ' ' ? { url: mineDetails.corporateVideo } : {},
          companyProfile: mineDetails.companyProfile,
          campusLowCarbon: mineDetails.campusLowCarbon,
          updataOraffirm: true,
          slogan: mineDetails.slogan,
        },
        () => {
          this.formRef?.current?.setFieldValue('coverImg', mineDetails.coverImage)
          this.formRef?.current?.setFieldValue('coverVideo', mineDetails.corporateVideo)
          this.formRef?.current?.setFieldValue('logoImg', mineDetails.companyLogo)
          this.formRef?.current?.setFieldValue('listImage', mineDetails.listImage)
          this.formRef?.current?.setFieldValue('companyProfile', mineDetails.companyProfile)
          this.formRef?.current?.setFieldValue('campusLowCarbon', mineDetails.campusLowCarbon)
          this.formRef?.current?.setFieldValue('slogan', mineDetails.slogan)
        },
      )
    }
  }

  componentDidUpdate(newProps) {}

  //封面图片上传
  onCoverImg = (data) => {
    console.log(data, 'data')
    if (data.file.size > 5242880) return message.error('文件大小最大为5mb！')
    // this.setState({
    //     fileListcover: data.fileList[0]
    // })
    const formData = new FormData()
    formData.delete('file')
    formData.append('file', data.file.originFileObj)
    if (data.file.status === 'uploading') {
      this.setState({
        coverSpin: true,
      })
      this.props.dispatch({
        type: 'projectModel/uploadFile',
        payload: {
          params: formData,
          callback: (item) => {
            console.log(item, 'item')
            this.setState({
              coverImg: { url: item.url },
              coverSpin: false,
            })
            this.formRef?.current?.setFieldValue('coverImg', item.url)
          },
        },
      })
    }
  }

  //学校视频上传
  onCoverVideo = (data) => {
    console.log(data, 'data')
    if (data.file.size > 5242880 * 4) return message.error('文件大小最大为20mb！')
    // this.setState({
    //     fileListcover: data.fileList[0]
    // })
    const formData = new FormData()
    formData.delete('file')
    formData.append('file', data.file.originFileObj)
    if (data.file.status === 'uploading') {
      this.setState({
        videoSpin: true,
      })
      this.props.dispatch({
        type: 'projectModel/uploadFile',
        payload: {
          params: formData,
          callback: (item) => {
            console.log(item, 'item')
            this.setState({
              coverVideo: { url: item.url },
              videoSpin: false,
            })
            this.formRef?.current?.setFieldValue('coverVideo', item.url)
          },
        },
      })
    }
  }

  //学校logo上传
  onCampusImg = (data) => {
    if (data.file.size > 5242880) return message.error('文件大小最大为5mb！')
    const formData = new FormData()
    formData.delete('file')
    formData.append('file', data.file.originFileObj)
    if (data.file.status === 'uploading') {
      this.setState({
        logoSpin: true,
      })
      this.props.dispatch({
        type: 'projectModel/uploadFile',
        payload: {
          params: formData,
          callback: (item) => {
            console.log(item, 'item')
            this.setState({
              logoImg: { url: item.url },
              logoSpin: false,
            })
            this.formRef?.current?.setFieldValue('logoImg', item.url)
          },
        },
      })
    }
  }

  //宣传图片上传
  onIntroduce = (data) => {
    if (data.file.size > 5242880) return message.error('文件大小最大为5mb！')
    const formData = new FormData()
    formData.delete('file')
    formData.append('file', data.file.originFileObj)
    if (data.file.status === 'uploading') {
      let { listImage } = this.state
      this.setState({
        listSpin: true,
      })
      this.props.dispatch({
        type: 'projectModel/uploadFile',
        payload: {
          params: formData,
          callback: (item) => {
            listImage.push({ url: item.url })
            this.setState(
              {
                listImage: listImage,
                listSpin: false,
              },
              () => {
                this.formRef?.current?.setFieldValue('listImage', listImage)
              },
            )
          },
        },
      })
    }
    if (data.file.status === 'removed') {
      let { listImage } = this.state
      for (let i in listImage) {
        if (data.file.url === listImage[i].url) {
          console.log(listImage[i], i, 'listImage[i]')
          listImage.splice(i, 1)
        }
      }
      this.setState(
        {
          listImage: listImage,
        },
        () => {
          console.log(this.state.listImage, 'this.state.listImage')
          this.formRef?.current.setFieldValue('listImage', this.state.listImage)
        },
      )
    }
  }

  //学校风采宣传text
  publicity = (e) => {
    this.setState({
      publicityText: e.target.value,
    })
  }

  //保存
  affirm = (data) => {
    // console.log(this.formRef?.current?.getFieldValue('campusLowCarbon'), 'data');
    if (this.formRef?.current?.getFieldValue('campusLowCarbon') === '<p><br></p>') {
      this.formRef?.current?.setFieldValue('campusLowCarbon', null)
    }
    if (this.formRef?.current?.getFieldValue('companyProfile') === '<p><br></p>') {
      this.formRef?.current?.setFieldValue('companyProfile', null)
    }
    this.formRef?.current?.validateFields().then((res) => {
      console.log(res, 'res')
      let { coverImg, logoImg, listImage, coverVideo, updateOraffirm, companyProfile, campusLowCarbon } = this.state
      let { mineDetails } = this.props
      if (updateOraffirm) {
        let params = {
          id: mineDetails.id,
          coverImage: res.coverImg,
          companyLogo: res.logoImg,
          listImage: res.listImage,
          companyProfile: res.companyProfile,
          campusLowCarbon: res.campusLowCarbon,
          corporateVideo: res.coverVideo,
          slogan: res.slogan,
          publicityImage: mineDetails.publicityImage,
        }
        console.log(params, 'params')
        this.props.updateMine(params)
      } else {
        this.props.addMine(
          res.coverImg,
          res.logoImg,
          res.listImage,
          res.coverVideo,
          res.companyProfile,
          res.campusLowCarbon,
          res.slogan,
        )
      }
    })
  }

  //编辑按钮
  upDate = () => {
    this.props.updateBtn()
    this.setState(
      {
        updateOraffirm: true,
      },
      () => {
        let { editor, editor2 } = this.state
        this.disables(editor)
        this.disables2(editor2)
      },
    )
  }

  //设置学校介绍富文本内容
  onCaseContent = (data) => {
    this.formRef?.current.setFieldValue('companyProfile', data)
  }

  //设置学校低碳富文本内容
  onCampusLowCarbon = (data) => {
    this.formRef?.current.setFieldValue('campusLowCarbon', data)
  }

  //设置学校介绍富文本状态
  disables = (data) => {
    let { mineState } = this.props
    this.setState({
      editor: data,
    })
    if (data && mineState) {
      data.disable()
    } else {
      data.enable()
    }
  }

  //设置学校低碳富文本状态
  disables2 = (data) => {
    let { mineState } = this.props
    this.setState({
      editor2: data,
    })
    if (data && mineState) {
      data.disable()
    } else {
      data.enable()
    }
  }

  removeVideo = () => {
    this.setState({
      coverVideo: {},
    })
    this.formRef?.current.setFieldValue('coverVideo', ' ')
  }

  render() {
    let { isModalOpen, mineState, mineDetails } = this.props
    let {
      listSpin,
      logoSpin,
      coverSpin,
      videoSpin,
      coverImg,
      listImage,
      logoImg,
      publicityText,
      coverVideo,
      companyProfile,
      campusLowCarbon,
      updateOraffirm,
      slogan,
    } = this.state
    console.log(...listImage, 'listImage')
    return (
      <React.Fragment>
        <Modal
          destroyOnClose={true}
          title="学校风采新增"
          open={isModalOpen}
          onCancel={() => {
            this.props.handleCancel(), this.setState({ updataOraffirm: false })
          }}
          footer={null}
          bodyStyle={{ height: 500, overflow: 'hidden', overflowY: 'auto' }}
          width={800}>
          <Form
            name="basic"
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 18,
            }}
            layout="Vertical"
            ref={this.formRef}>
            <Row align="top">
              <Col span={24} push={0} pull={3}>
                <Form.Item
                  label="学校标语"
                  name="slogan"
                  rules={[
                    {
                      required: true,
                      message: '请填写学校标语!',
                    },
                  ]}>
                  <Input showCount maxLength={20} disabled={mineState} placeholder={'请填写学校标语'}></Input>
                </Form.Item>
              </Col>
              <Col span={12} push={0}>
                <Form.Item
                  label="封面图片"
                  name="coverImg"
                  rules={[
                    {
                      required: true,
                      message: '请上传封面图片!',
                    },
                  ]}>
                  <Spin tip={'上传中'} style={{ fontSize: 12 }} spinning={coverSpin}>
                    <Upload
                      listType="picture-card"
                      onChange={this.onCoverImg}
                      fileList={Object.keys(coverImg).length > 0 ? [coverImg] : []}
                      name="file"
                      accept=".jpeg,.png,.jpg"
                      disabled={mineState}
                      onRemove={() => {
                        this.setState({ coverImg: {} })
                      }}
                      onPreview={() => {
                        window.open(coverImg.url)
                      }}
                      // progress={this.state.progress}
                    >
                      {Object.keys(coverImg).length <= 0 ? (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}> 上传 </div>
                        </div>
                      ) : null}
                    </Upload>
                  </Spin>
                  <div style={{ color: '#9a9a9a', marginTop: 5, fontSize: 12 }}>
                    允许上传png、jpg、jpeg格式，最大允许上传5M;（建议图片尺寸1125px*774px）
                  </div>
                </Form.Item>
              </Col>
              <Col span={12} push={0}>
                <Form.Item label="学校视频" name="coverVideo">
                  <Spin tip={'上传中'} style={{ fontSize: 12 }} spinning={videoSpin}>
                    <Upload
                      listType="picture-card"
                      onChange={this.onCoverVideo}
                      fileList={Object.keys(coverVideo).length > 0 ? [coverVideo] : null}
                      name="file"
                      accept=".mp4,.mov,.wmv,.flv,.avi,.mkv"
                      disabled={mineState}
                      onRemove={this.removeVideo}
                      onPreview={(data) => {
                        window.open(data.url)
                      }}>
                      {Object.keys(coverVideo).length <= 0 ? (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}> 上传 </div>
                        </div>
                      ) : null}
                    </Upload>
                  </Spin>
                  <div style={{ color: '#9a9a9a', marginTop: 5, fontSize: 12 }}>
                    允许上传mp4、mov、wmv、flv、avi、mkv格式，最大允许上传20M
                  </div>
                </Form.Item>
              </Col>
              <Col span={12} push={0}>
                <Form.Item
                  label="学校logo"
                  name="logoImg"
                  rules={[
                    {
                      required: true,
                      message: '请输入学校logo!',
                    },
                  ]}>
                  <Spin tip={'上传中'} style={{ fontSize: 12 }} spinning={logoSpin}>
                    <Upload
                      listType="picture-card"
                      onChange={this.onCampusImg}
                      fileList={Object.keys(logoImg).length > 0 ? [logoImg] : []}
                      disabled={mineState}
                      accept=".jpeg,.png,.jpg"
                      onRemove={() => {
                        this.setState({ logoImg: {} })
                      }}
                      onPreview={() => {
                        window.open(logoImg.url)
                      }}>
                      {Object.keys(logoImg).length <= 0 ? (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>上传</div>
                        </div>
                      ) : null}
                    </Upload>
                  </Spin>
                  <div style={{ color: '#9a9a9a', marginTop: 5, fontSize: 12 }}>
                    允许上传png、jpg、jpeg格式，最大允许上传5M;（建议图片尺寸162px*162px）
                  </div>
                </Form.Item>
              </Col>
              <Col span={12} push={0}>
                <Form.Item
                  label="宣传图片"
                  name="listImage"
                  rules={[
                    {
                      required: true,
                      message: '请上传宣传图片!',
                    },
                  ]}>
                  <Spin tip={'上传中'} style={{ fontSize: 12 }} spinning={listSpin}>
                    <Upload
                      key={JSON.stringify(listImage)}
                      listType="picture-card"
                      onChange={this.onIntroduce}
                      fileList={listImage?.length > 0 ? listImage : []}
                      disabled={mineState}
                      onPreview={(data) => {
                        console.log(data, 'windows')
                        window.open(data.url)
                      }}
                      accept=".png,.jpg,.jpeg">
                      {Object.keys(listImage).length < 5 ? (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>上传</div>
                        </div>
                      ) : null}
                    </Upload>
                  </Spin>
                  <div style={{ color: '#9a9a9a', marginTop: 5, fontSize: 12 }}>
                    允许上传png、jpg、jpeg格式，最大允许上传5M;（建议图片尺寸1125px*771px,最多可上传五张）
                  </div>
                </Form.Item>
              </Col>
              <Col span={24} push={0} pull={3}>
                <Form.Item
                  label="学校介绍"
                  name="companyProfile"
                  rules={[
                    {
                      required: true,
                      message: '请填写学校介绍!',
                    },
                  ]}>
                  <WangEditor
                    disable={this.disables}
                    onChangeValue={this.onCaseContent}
                    html={companyProfile}
                    placeholder="请填写案例内容..."
                    style={{ height: '200px' }}
                  />
                </Form.Item>
              </Col>
              <Col span={24} push={0} pull={3}>
                <Form.Item
                  label="学校低碳"
                  name="campusLowCarbon"
                  // rules={[
                  //     {
                  //         required: true,
                  //         message: '请填写学校低碳!',
                  //     },
                  // ]}
                >
                  <WangEditor
                    disable={this.disables2}
                    onChangeValue={this.onCampusLowCarbon}
                    html={campusLowCarbon}
                    placeholder="请填写案例内容..."
                    style={{ height: '200px' }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <div className={styles.functionBtn}>
              {mineState ? (
                <div className={styles.affirm} onClick={this.upDate}>
                  {'编辑'}
                </div>
              ) : (
                <div type="primary" className={styles.affirm} onClick={this.affirm}>
                  {'保存'}
                </div>
              )}
              <div
                className={styles.cancel}
                onClick={() => {
                  this.props.handleCancel(), this.setState({ updateOraffirm: false })
                }}>
                取消
              </div>
            </div>
          </Form>
        </Modal>
      </React.Fragment>
    )
  }
}
